package com.itheima.config;

import com.alibaba.fastjson.JSON;
import com.itheima.bean.Employee;
import com.itheima.common.R;
import com.itheima.dao.UserDao;
import com.itheima.dao.employeeDao;
import com.itheima.security.MyUsernamePasswordAuthenticationFilter;
import com.itheima.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private employeeDao employeeDao;


    @Bean
    public BCryptPasswordEncoder bcr(){
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //auth.userDetailsService(new UserDetailsService() {
        //    @Override
        //    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //
        //        return employeeDao.findByUsername(username);
        //    }
        //});

      //lamda 格式
        auth.userDetailsService(username ->{

            Employee e = employeeDao.findByUsername(username);
                    System.out.println("e = " + e);
                    return e;
                }



        );
    }

    @Bean
    public MyUsernamePasswordAuthenticationFilter MyUsernamePasswordAuthenticationFilter() throws Exception {

        MyUsernamePasswordAuthenticationFilter  filter = new MyUsernamePasswordAuthenticationFilter();

        filter.setFilterProcessesUrl("/employee/login");
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.setAuthenticationSuccessHandler((req,resp,auth)->{

            resp.setContentType("application/json;charset=utf-8");
            Employee e = (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            resp.getWriter().write(JSON.toJSONString(R.success(e)));

        });
        filter.setAuthenticationFailureHandler((req,resp,auth)->{

            resp.setContentType("application/json;charset=utf-8");

            resp.getWriter().write(JSON.toJSONString(R.error("登录失败！")));
        });


        return filter;



    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.authorizeRequests()
                .antMatchers("/backend/page/login/login.html","/user/**",
                        "/front/**","/**/*.js" , "/**/*.css" ,
                        "/**/styles/**","/**/sms/**" , "/**/*.ico" ,"/**/plugin/**", "/**/images/**").permitAll()
                .antMatchers("/**/backend/**").authenticated()
                .anyRequest().permitAll()
                .and().formLogin().loginPage("/backend/page/login/login.html").loginProcessingUrl("/backend/page/login/login.html")
                .and().logout().logoutUrl("/logout").logoutSuccessHandler((req,resp,auth)->{

                    resp.setContentType("application/json;charset=utf-8");
                    resp.getWriter().write(JSON.toJSONString(R.success("退出登录成功！")));

        })
                .and().headers().frameOptions().sameOrigin() //加入同源策略，这样即可允许页面上加载iframe子页面
                .and().csrf().disable();

        http.exceptionHandling().accessDeniedHandler((req,resp,auth)->{
            resp.setContentType("application/json;charset=utf-8");

            resp.getWriter().write(JSON.toJSONString(R.error("权限不足，禁止访问！")));
        });

        http.addFilterAt(MyUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
